﻿Imports System.Data
Imports CrystalDecisions.Shared
Imports CrystalDecisions.CrystalReports.Engine
Imports System.Data.OleDb
Imports System
Imports System.Globalization

Partial Class Interfaz_frmAdminOrdenDeCompra
    Inherits System.Web.UI.Page
    Dim CL As New ControladorLogica
    Dim dtDatos As New DataTable
    Dim dataset As New DataSet


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If CL.visibilidadesFormsInternos("Administracion", Session("user").ToString) = False Then
            Response.Redirect("Index.aspx")
        End If
        Dim i As Integer
        Dim ArrayRequisicion As New ArrayList

        ArrayRequisicion = CL.ObtenerRequisicionPendientes()

        If Not Page.IsPostBack Then
            For i = 0 To ArrayRequisicion.Count - 1
                Me.DropReq.Items.Add(DirectCast(ArrayRequisicion.Item(i), Requisicion).Id)
            Next
        End If

        'se guardan datos en secion para el positback de la pagina respecto al los datos del datagridview
        If Session("OrdenCompra") Is Nothing Then
            Session("OrdenCompra") = dtDatos
        Else
            dtDatos = DirectCast(Session("OrdenCompra"), DataTable)

        End If

        If Not Page.IsPostBack Then
            Try
                dtDatos.Columns.Add(New DataColumn("ITEM"))
                dtDatos.Columns.Add(New DataColumn("UNIDAD"))
                dtDatos.Columns.Add(New DataColumn("DETALLE"))
                dtDatos.Columns.Add(New DataColumn("CANTIDAD"))
                dtDatos.Columns.Add(New DataColumn("PRECIOUNITARIO"))
                dtDatos.Columns.Add(New DataColumn("CODMATERIAL"))

                Me.GridOrdenCompra.DataBind()
                Me.GridOrdenCompra.DataSource = Me.dtDatos

            Catch
            End Try
        End If
        ' Me.GridRequisicion.DataBind()
        Me.GridOrdenCompra.DataSource = Me.dtDatos

    End Sub

#Region "Funcionalidades"

    Public Sub Mensaje(ByVal msg As String)
        Dim alertScript As String = "<script language=JavaScript runat=server>"
        alertScript &= "alert('" & msg & "');"
        alertScript &= "</script>"
        ClientScript.RegisterClientScriptBlock(Page.GetType(), "clientScrip", alertScript)
    End Sub

    Private Sub LimpiarTodo()
        Me.TxtAtencion.Text = String.Empty
        Me.TxtComprador.Text = String.Empty
        Me.TxtCondVenta.Text = String.Empty
        Me.TxtDespacho.Text = String.Empty
        Me.TxtNotas.Text = String.Empty
    End Sub

    Private Sub CargarRequisicion()
        Dim numeroRequisicion As String = Me.DropReq.Text
        Dim query As String = "select * from requisicion where id =" + numeroRequisicion
        Dim arrayReq As ArrayList = CL.ObtenerRequisicionItem(numeroRequisicion, Me.DropProveedor.Text)
        Dim i As Integer

        vaciaGrid()

        For i = 0 To arrayReq.Count - 1
            Dim drDatos As DataRow = dtDatos.NewRow
            Dim item As ItemDocumentos = DirectCast(arrayReq.Item(0), ItemDocumentos)
            query = "select codmaterial from material where id =" + item.Fkmaterial
            Dim codMaterial As String = CL.Ejecuta(query).Item("codmaterial").ToString

            drDatos.Item("ITEM") = item.ITEM
            drDatos.Item("UNIDAD") = item.Unidad
            drDatos.Item("DETALLE") = item.Detalle
            drDatos.Item("CANTIDAD") = item.Cantidad
            drDatos.Item("PRECIOUNITARIO") = item.PrecioUnitario
            drDatos.Item("CODMATERIAL") = codMaterial

            dtDatos.Rows.Add(drDatos)

            Me.GridOrdenCompra.DataSource = dtDatos
            Me.GridOrdenCompra.DataBind()
        Next

    End Sub

    Public Sub CargarProveedoresRequisicion()
        Dim numeroReq As String = Me.DropReq.Text
        Dim ArrayItemReqFaltante As ArrayList = CL.ObtenerRequisicionItem(numeroReq)
        Me.DropProveedor.Items.Clear()
        Me.DropProveedor.Items.Add("-----")
        For i As Integer = 0 To ArrayItemReqFaltante.Count - 1
            Dim item As ItemDocumentos = DirectCast(ArrayItemReqFaltante.Item(i), ItemDocumentos)
            If item.FKProveedor <> "-----" Then
                Dim query As String = "select * from proveedor where rut='" + item.FKProveedor + "'"
                Dim prov As Proveedor = DirectCast(CL.ObtenerProveedor(query).Item(0), Proveedor)

                Dim itemLista As New ListItem
                itemLista.Text = prov.Rznsocial
                itemLista.Value = item.FKProveedor

                Me.DropProveedor.Items.Add(itemLista)
            End If
        Next
    End Sub

    Private Sub vaciaGrid()
        dtDatos = DirectCast(Session("OrdenCompra"), DataTable)
        If Not dtDatos Is Nothing Then
            dtDatos.Clear()
            Session("OrdenCompra") = dtDatos
        End If
        Me.GridOrdenCompra.DataSource = Nothing
        Me.GridOrdenCompra.DataBind()
    End Sub

    Private Sub CargarOrdenCompraBD()
        Dim fkRequisicion As String = Me.DropReq.Text
        Dim nombreProveedor As String = Me.DropProveedor.Text
        Dim Atencion As String = Me.TxtAtencion.Text
        Dim condPago As String = Me.TxtCondVenta.Text
        Dim despachar As String = Me.TxtDespacho.Text
        Dim fecha As String = Me.BasicDatePicker1.Text
        Dim rutProv As String = DirectCast(CL.ObtenerProveedorID(Me.DropProveedor.SelectedValue).Item(0), Proveedor).Rut
        Dim Comprador As String = Me.TxtComprador.Text
        Dim notas As String = Me.TxtNotas.Text
        Dim filaGrid As GridViewRow
        Dim arrayItemOC As New ArrayList



        With Me.GridOrdenCompra
            For fila As Integer = 0 To .Rows.Count - 1
                filaGrid = .Rows(fila)
                Dim cb As CheckBox = filaGrid.FindControl("itemSelector")

                If cb.Checked = True Then
                    Dim item As String = filaGrid.Cells(1).Text
                    Dim unidad As String = filaGrid.Cells(2).Text
                    Dim detalle As String = filaGrid.Cells(3).Text
                    Dim cantidad As String = filaGrid.Cells(4).Text
                    Dim precioUnitario As String = filaGrid.Cells(5).Text
                    Dim codMaterial As String = filaGrid.Cells(6).Text

                    Dim query As String = "select id from material where codmaterial='" + codMaterial + "'"
                    Dim fkmaterial As String = CL.Ejecuta(query).Item("id").ToString
                    Dim itemDoc As New ItemDocumentos("", item, unidad, detalle, cantidad, precioUnitario, fkmaterial, fkRequisicion)


                    arrayItemOC.Add(itemDoc)
                    CL.ActualizarRequisicionItem(fkRequisicion, fkmaterial, rutProv)
                End If
            Next
        End With

        Dim nuevaOrden As New OrdenCompra(0, fecha, fecha)
        nuevaOrden.arrayItemOC = arrayItemOC
        nuevaOrden.Atencion = Atencion
        nuevaOrden.Comprador = Comprador
        nuevaOrden.condPago = condPago
        nuevaOrden.despachar = despachar
        nuevaOrden.fkRequisicion = fkRequisicion
        nuevaOrden.rutProv = rutProv
        nuevaOrden.notas = notas
        nuevaOrden.nombreProveedor = nombreProveedor

        CL.insertarOrdenCompra(nuevaOrden)
        CL.ActualizarRequisicion(fkRequisicion)
    End Sub

#End Region

#Region "Botones"

    Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
        Me.LimpiarTodo()
    End Sub

    Protected Sub BtnSeleccion_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSeleccion.Click
        CargarProveedoresRequisicion()
    End Sub

    Protected Sub BtnSelectProv_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSelectProv.Click
        Me.CargarRequisicion()
    End Sub

    Protected Sub BtnValidar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnValidar.Click
        CargarOrdenCompraBD()
        Me.Mensaje("La orden de compra ha sido cargada exitosamente")
        LimpiarTodo()
        vaciaGrid()
    End Sub
#End Region

#Region "Eventos Grid"
    'Grid Material
    Protected Sub GridOrdenCompra_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
        GridOrdenCompra.PageIndex = e.NewPageIndex
        'Bind data to the GridView control.
        GridOrdenCompra.DataSource = Session("OrdenCompra")
        GridOrdenCompra.DataBind()
    End Sub

    Protected Sub GridOrdenCompra_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
        'Set the edit index.
        GridOrdenCompra.EditIndex = e.NewEditIndex
        'Bind data to the GridView control.
        GridOrdenCompra.DataSource = Session("OrdenCompra")
        GridOrdenCompra.DataBind()
    End Sub

    Protected Sub GridOrdenCompra_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
        'Reset the edit index.
        GridOrdenCompra.EditIndex = -1
        'Bind data to the GridView control.
        GridOrdenCompra.DataSource = Session("OrdenCompra")
        GridOrdenCompra.DataBind()
    End Sub

    Protected Sub GridOrdenCompra_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
        'Retrieve the table from the session object.
        Dim dt As DataTable = CType(Session("OrdenCompra"), DataTable)

        'Update the values.
        Dim row As GridViewRow = GridOrdenCompra.Rows(e.RowIndex)
        'Dim actividad As String = (CType((row.Cells(2).Controls(0)), TextBox)).Text.ToString
        Dim CODIGO As String = (CType((row.Cells(2).Controls(0)), TextBox)).Text
        Dim DETALLE As String = (CType((row.Cells(3).Controls(0)), TextBox)).Text
        Dim CANTIDAD As String = (CType((row.Cells(4).Controls(0)), TextBox)).Text
        Dim PRECIOUNITARIO As String = (CType((row.Cells(5).Controls(0)), TextBox)).Text

        'dt.Rows(row.DataItemIndex)("ITEM") = actividad
        dt.Rows(row.DataItemIndex)("CODIGO") = CODIGO
        dt.Rows(row.DataItemIndex)("DETALLE") = DETALLE
        dt.Rows(row.DataItemIndex)("CANTIDAD") = CANTIDAD
        dt.Rows(row.DataItemIndex)("PRECIOUNITARIO") = PRECIOUNITARIO

        'Reset the edit index.
        GridOrdenCompra.EditIndex = -1

        'Bind data to the GridView control.
        GridOrdenCompra.DataSource = Session("OrdenCompra")
        GridOrdenCompra.DataBind()
    End Sub

    Sub GridOrdenCompra_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
        Dim dt As DataTable = CType(Session("OrdenCompra"), DataTable)
        dt.Rows(e.RowIndex).Delete()
        GridOrdenCompra.DataSource = dt
        GridOrdenCompra.DataBind()
    End Sub
#End Region
    
    
   
   
   
End Class
